﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.Linq;
using System.IO;

namespace Paypayes.Inventory
{
    public partial class MainForm : Form
    {
        private static XElement _xElem = null;

        public static XElement XElem
        {
            get
            {
                return _xElem;
            }
        }

        public static Boolean IsModifying = false;
        public static Dictionary<String, Image> thumbnails = new Dictionary<string, Image>();

        public MainForm()
        {
            try
            {
                _xElem = XElement.Load("inventaire.xml");
            }
            catch (System.IO.FileNotFoundException)
            {
                _xElem = new XElement("inventory");
            }
            catch (Exception)
            {
                MessageBox.Show("fichier inventaire corrompu");
            }

            // create thumbnails
            foreach (XElement elem in _xElem.Nodes())
            {
                Image image = null;
                try
                {
                    image = Image.FromFile(elem.Element("picture").Value);
                }
                catch (Exception)
                {
                    // XXX remplacer par une image interne!
                    image = Image.FromFile(@"vide.jpg");
                }
                thumbnails.Add(elem.Attribute("id").Value, image.GetThumbnailImage(120, 120, () => false, IntPtr.Zero));
            }
            InitializeComponent();
        }

        private void btnAddItem_Click(object sender, EventArgs e)
        {
            AddChangeItemForm form = new AddChangeItemForm();
            form.Text = "Ajouter un vêtement";
            form.Show(this);
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            _xElem.Changed += new EventHandler<XObjectChangeEventArgs>(_xElem_Changed);

            CreatePage("");
        }

        void _xElem_Changed(object sender, XObjectChangeEventArgs e)
        {
            if (!IsModifying)
            {
                _xElem.Save("inventaire.xml");
                foreach (TabPage page in tabControl1.TabPages)
                {
                    ((ItemsListView)page.Controls[0]).GenerateList(((ItemsListView)page.Controls[0]).Filter);
                }
            }
            else
            {
                IsModifying = false;
            }
        }

        private void CreatePage(String filter)
        {
            TabPage page = new TabPage();
            ItemsListView ilv = new ItemsListView();
            ilv.Dock = DockStyle.Fill;

            if (tabControl1.TabPages.Count > 0)
            {
                page.Text = filter;
            }
            else
            {
                page.Text = "tout";
            }
            page.Controls.Add(ilv);
            ilv.GenerateList(filter);

            tabControl1.TabPages.Add(page);
            tabControl1.SelectedTab = page;
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            CreatePage(txtSimpleSearch.Text);
        }

        private void listView1_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
        {
            if (e.Header.Index == 4)
            {

                if (((ItemContext)e.Item.Tag).Thumbnail == null)
                {
                    Image image = null;
                    try
                    {
                        image = Image.FromFile(((ItemContext)e.Item.Tag).PicturePath);
                    }
                    catch (Exception)
                    {
                        image = Image.FromFile(@"vide.jpg");
                    }
                    ((ItemContext)e.Item.Tag).Thumbnail = image.GetThumbnailImage(120, 120, () => false, IntPtr.Zero);
                }
                e.Graphics.DrawImage(((ItemContext)e.Item.Tag).Thumbnail, e.Bounds.X + 5, e.Bounds.Y + 5);
            }
            else
            {
                e.DrawDefault = true;
            }
        }

        private void listView1_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
        {
            e.DrawDefault = true;
        }

        private void listView1_DrawItem(object sender, DrawListViewItemEventArgs e)
        {
            e.DrawDefault = false;
        }

        private void listView1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if ((tabControl1.TabPages[0].Controls[0] as ListView).SelectedItems != null)
            {
                AddChangeItemForm form = new AddChangeItemForm();
                form.Text = "Modifier un vêtement";
                form.Initialize(((ItemContext)(tabControl1.TabPages[0].Controls[0] as ListView).SelectedItems[0].Tag).Element);
                IsModifying = true;
                form.ShowDialog(this);
                IsModifying = false;
            }
        }

        private void tabControl1_MouseClick(object sender, MouseEventArgs e)
        {
            // check if the right mouse button was pressed
            if (e.Button == MouseButtons.Right)
            {
                // iterate through all the tab pages
                for (int i = 1; i < tabControl1.TabCount; i++)
                {
                    // get their rectangle area and check if it contains the mouse cursor
                    Rectangle r = tabControl1.GetTabRect(i);
                    if (r.Contains(e.Location))
                    {
                        tabControl1.TabPages.RemoveAt(i);
                    }
                }
            }
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            // XXX refaire ça propre
            XElement elmTable = new XElement("table",
                new XAttribute("border", "1"),
                new XElement("tr",
                    new XElement("th", "description"),
                    new XElement("th", "tailles enfants"),
                    new XElement("th", "tailles adultes"),
                    new XElement("th", "carton"),
                    new XElement("th", "image")));

            XDocument xDoc = new XDocument(
                new XDeclaration("1.0", "UTF-16", null),
                new XElement("html",
                    new XElement("body", elmTable)));
            foreach(ListViewItem item in ((ItemsListView)tabControl1.SelectedTab.Controls[0]).ef())
            {
                elmTable.Add(new XElement("tr",
                            new XElement("td", item.SubItems[1].Text),
                            new XElement("td", item.SubItems[2].Text),
                            new XElement("td", item.SubItems[3].Text),
                            new XElement("td", item.SubItems[4].Text),
                            new XElement("td",
                                new XElement("img",
                                    new XAttribute("src", String.Format("file:///{0}", item.SubItems[5].Text)),
                                    new XAttribute("width", "200"),
                                    new XAttribute("height", "200")))));
            }

            // Save to Disk
            xDoc.Save("inventaire.html");
        }
    }

    public class ItemContext
    {
        public Image Thumbnail { get; set; }
        public String PicturePath { get; set; }
        public XElement Element { get; set; }
    }
}
